package com.umpay.privi.dao.on.sys.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.ibatis.SqlMapClientCallback;

import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.umpay.common.persist.AbstractDao;
import com.umpay.common.persist.ibatis.DataAccessException;
import com.umpay.common.persist.ibatis.exception.SQLErrorCodeSQLExceptionTranslator;
import com.umpay.privi.dao.EntityDaoImpl;
import com.umpay.privi.dao.on.sys.PrivilegeMenuDao;
import com.umpay.privi.model.sys.PrivilegeMenu;

public class PrivilegeMenuDaoImpl extends EntityDaoImpl<PrivilegeMenu> implements PrivilegeMenuDao{

	private static Logger log = LoggerFactory.getLogger(PrivilegeMenuDaoImpl.class);
	
	
	@SuppressWarnings("unchecked")
	public List<PrivilegeMenu> findList(Map<String, Object> map)
			throws DataAccessException {
		try {
			return getSqlMapClient().queryForList("PrivilegeMenu.Find", map);
		} catch (SQLException e) {
			throw new SQLErrorCodeSQLExceptionTranslator(AbstractDao.DB_TYPE_DB2).translate(e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	public void insertBatch(final List<PrivilegeMenu> list)
			throws DataAccessException {
		if (null == list || list.size() == 0) {
			log.error("角色权限关系为空！");
			return;
		}
		SqlMapClientCallback callback = new SqlMapClientCallback() {
			public Object doInSqlMapClient(SqlMapExecutor sqlMapExecutor)
					throws SQLException {
				int counter = 0;
				sqlMapExecutor.startBatch();
				for (PrivilegeMenu privilegeMenu : list) {
					PrivilegeMenu resObj=(PrivilegeMenu)sqlMapExecutor.queryForObject("PrivilegeMenu.GetMap",privilegeMenu);//get
					privilegeMenu.setFlag("0");
					if(resObj==null){
						sqlMapExecutor.insert("PrivilegeMenu.Insert", privilegeMenu);//insert
					}else{
						sqlMapExecutor.insert("PrivilegeMenu.Update", privilegeMenu);//update
					}
					counter++;
					if (counter % 1000 == 0) {
						// 设置一个计数器每隔1000条提交一次
						sqlMapExecutor.executeBatch();
						sqlMapExecutor.startBatch();
					}
				}
				sqlMapExecutor.executeBatch();
				return null;
			}
		};
		this.getSqlMapClientTemplate().execute(callback);
	}

	public void updatePrivilegeMenu(Map<String, Object> map)
			throws DataAccessException {
		try {
			getSqlMapClient().update("PrivilegeMenu.UpdatePrivilegeMenu", map);
		} catch (SQLException e) {
			throw new SQLErrorCodeSQLExceptionTranslator(AbstractDao.DB_TYPE_DB2).translate(e.getMessage(), e);
		}
	}



}
